import { deleteInstrument, listInstrument } from '@/services/api/instrument';
import { convertPageData } from '@/utils/request';
import { openConfirm } from '@/utils/ui';
import { PlusOutlined, DeleteOutlined, ToolOutlined, FullscreenExitOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { ReactNode, useRef, useState } from 'react';
import InputDialog from './InputDialog';
import { repairByCodes } from '@/services/api/instrument';
import { repairedByCodes } from '@/services/api/instrument';




export default () => {
  const refAction = useRef<ActionType>(null);
  const [selectedRowKeys, selectRow] = useState<number[]>([]);
  const [instrument, setInstrument] = useState<API.InstrumentVO>();
  const [visible, setVisible] = useState(false);
  
  const columns: ProColumns<API.InstrumentVO>[] = [
    {
      title: '仪器ID',
      dataIndex: 'id',
      width: 100,
      search: false,
    },
    {
      title: '仪器名称',
      dataIndex: 'instrumentName',
      width: 150,
      render: (dom, record) => {
        return (
          <a
            onClick={() => {
              setInstrument(record);
              setVisible(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '仪器总量',
      dataIndex: 'totalNumber',
      width: 100,
      search: false,
    },
    {
      title: '损坏仪器数量',
      dataIndex: 'availableNumber',
      width: 110,
      search: false,
      render: (text) => {
        const isZero = text === 0;
        return (
          <div style={{ color: isZero ? 'inherit' : 'red' }}>
            {text}
          </div>
        );
      },
    },
    {
      title: '房间号',
      dataIndex: 'roomNumber',
      width: 100,
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 90,
      search:false,
      render: (value: ReactNode, entity: API.InstrumentVO, index: number) => {
      if (typeof value === 'number') {
        // 判断数据类型是 number，就前面加上 $
        return `$${value}`;
      }
      return '';
    }, 
    },
    {
      title: '是否报修',
      dataIndex: 'returned',
      width: 100,
      search: false,
    },
    {
        title: '领用人',
        dataIndex: 'borrowedBy',
        width: 100,
    },
    {
      title: '领用时间',
      dataIndex: 'receivingAt',
      width: 150,
      search: false,
    },
    {
      title: '价格下限',
      dataIndex: 'minPrice',
      hideInTable:true,
    },
    {
      title: '价格上限',
      dataIndex: 'maxPrice',
      width: 20,
      hideInTable:true,
    },
    {
      title: '质检员',
      dataIndex: 'managerDesc',
      width: 100,
      search: false,
    },
    {
        title: '质检员联系方式',
        dataIndex: 'phoneNumber',
        width: 120,
        search: false,
    }, 
  
  ];

  const handleDelete = async () => {
    if (!selectedRowKeys?.length) return;
    openConfirm(`您确定删除${selectedRowKeys.length}条记录吗`, async () => {
      await deleteInstrument(selectedRowKeys);
      refAction.current?.reload();
      message.success("删除成功");
    });
  };



  const repairing = async () => {
    if (!selectedRowKeys?.length) return;
    openConfirm(`您确定报修${selectedRowKeys.length}种实验仪器吗`, async () => {
      await repairByCodes(selectedRowKeys);      
      refAction.current?.reload();
      message.success("报修成功");
    }
     );
  };


  const repaired = async () => {
    if (!selectedRowKeys?.length) return;
    openConfirm(`您确定${selectedRowKeys.length}条记录中的实验仪器已经维修完毕吗`, async () => {
      await repairedByCodes(selectedRowKeys);      
      refAction.current?.reload();
      message.success("维修仪器更新成功");
    }
     );
  };



  return (
    <PageContainer>
      <ProTable<API.InstrumentVO>
        
        actionRef={refAction}
        rowKey="id"
        request={async (params = {}) => {
          return convertPageData(await listInstrument(params));
        }}
        
        toolBarRender={() => [
          <>
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setInstrument(undefined);
              setVisible(true);
            } }
          >
              <PlusOutlined /> 新建
            </Button></>,
          <Button
            type="primary"
            key="primary"
            danger
            disabled={!selectedRowKeys?.length}
            onClick={handleDelete}
          >
            <DeleteOutlined /> 删除
          </Button>,

          <Button
          type="primary"
          key="primary"
          onClick={repairing}
          disabled={!selectedRowKeys?.length}
        >
          <ToolOutlined /> 报修
        </Button>,
          <Button
          type="primary"
          key="primary"
          onClick={repaired}
          disabled={!selectedRowKeys?.length}
        >
          <FullscreenExitOutlined /> 维修完毕
        </Button>
        ]}
        columns={columns}
        rowSelection={{
          onChange: (rowKeys) => {
            selectRow(rowKeys as number[]);
          },
        }}
      />
      <InputDialog
        detailData={instrument}
        onClose={(result: any) => {
          setVisible(false);
          result && refAction.current?.reload();
        }}
        visible={visible}
      />
    </PageContainer>
  );
    
};